package com.hangman;

import java.util.ArrayList;

public class Hangman {
	private int currentTask = 0;
	private int[] showingIndexes;
	private ArrayList<Task> tasks;
	private int wins, losses, wordsTotal, wordsPlayed = 0;
	private int triesLeft = 10;
	private ArrayList<Character> wrongLetters;

	public Hangman(Category category, int numberOfWords) {
		tasks = category.getRandomTasks(numberOfWords);
		hideAllLetters();
		// This table will control which characters that are guessable
		wrongLetters = new ArrayList<Character>();
	}

	public int test() {
		return currentTask;
	}

	public boolean makeGuess(char guess) {
		if (tasks.get(currentTask).checkIfContains(guess)) {
			for (int i = 0; i < getCurrentWord().length(); i++) {
				if (Character.toLowerCase(getCurrentWord().charAt(i)) == Character
						.toLowerCase(guess)) {
					showingIndexes[i] = 1;
				}
			}
			return true;
		}
		wrongLetters.add(guess);
		triesLeft--;
		return false;
	}

	public int getTriesLeft() {
		return triesLeft;
	}

	public int getNumberOfTasks() {
		return tasks.size();
	}

	public Task getCurrentTask() {
		return tasks.get(currentTask);
	}

	public boolean nextWord() {
		if (currentTask < getNumberOfTasks() - 1) {
			currentTask++;
			triesLeft = 10;
			wrongLetters = new ArrayList<Character>();
			return true;
		} else
			return false;
	}

	public int[] getShowingIndexes() {
		return showingIndexes;
	}

	public void showAllLetters() {
		for (int i = 0; i < showingIndexes.length; i++) {
			showingIndexes[i] = 1;
		}
	}

	private void hideAllLetters() {
		showingIndexes = new int[tasks.get(currentTask).getWordLength()];
		for (int i = 0; i < showingIndexes.length; i++) {
			showingIndexes[i] = 0;
		}
	}

	public String getCurrentWord() {
		return tasks.get(currentTask).toString();
	}

	public boolean checkIfLost() {
		wordsPlayed = wordsTotal - (wins + losses);
		if (triesLeft <= 0) {
			losses++;
			nextWord();
			hideAllLetters();
			return true;
		}
		return false;
	}

	public boolean checkIfWon() {
		for (int i = 0; i < showingIndexes.length; i++) {
			if (showingIndexes[i] == 0) {
				return false;
			}
		}
		wins++;
		wordsPlayed = wordsTotal - (wins + losses);
		nextWord();
		hideAllLetters();
		return true;
	}
	
	public boolean checkIfFinished(){
		if(tasks.size() == wins+losses) return true;
		else return false;
	}

	public int getWins() {
		return wins;
	}

	public int getLosses() {
		return losses;
	}

	public int getWordsPlayed() {
		return wordsPlayed;
	}

	public String getWrongLetters() {
		String letters = "";
		for(Character c : wrongLetters){
			letters += " " + c.toString();
		}
		return letters;
	}

	public void setWrongLetters(ArrayList<Character> wrongLetters) {
		this.wrongLetters = wrongLetters;
	}

}
